package com.coder.algorithm.leetcode

import com.coder.algorithm.struct.ListNode

/**
 * [2. 两数相加](https://leetcode-cn.com/problems/add-two-numbers/)
 *
 * @author yuhus
 * @date: 2022/4/7
 */
object l_0002 {
    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
        val preHead = ListNode(-1)
        var prev = preHead
        var p1 = l1
        var p2 = l2
        var bit = 0
        var sum: Int
        while (p1 != null || p2 != null) {
            sum = bit
            if (p1 != null) {
                sum += p1.`val`
            }
            if (p2 != null) {
                sum += p2.`val`
            }
            bit = sum / 10
            sum %= 10
            val cur = ListNode(sum)
            prev.next = cur
            prev = cur
            p1 = p1?.next
            p2 = p2?.next
        }
        if (bit > 0) {
            prev.next = ListNode(bit)
        }
        return preHead.next
    }
}